2
2
.
.
8
8
.
.
4
4
I
I
n
n
s
s
t
t
a
a
n
n
t
t
i
i
a
a
t
t
e
e
S
S
e
e
r
r
v
v
i
i
c
c
e
e
-
-
U
U
s
s
i
i
n
n
g
g
C
C
l
l
a
a
s
s
s
s
-
-
@
@
A
A
u
u
t
t
o
o
w
w
i
i
r
r
e
e
d
d
I
I
n
n
f
f
o
o
[
[
G
G
]
]
Previous example can be simplified by using @Autowired to tell Spring to create Service Instance.
This way we don't need to manually create Service Instance inside the Controller's endpoint.
But with this approach we are tightly coupling Controller with specific Service implementation.
This means that if we want to use different Service Class that implements this part of business logic we would still need to
make changes to the Controller which increases our workload and potentially introduces bugs in it.
So a more elegant solution would be to use Service Interface inside the Controller.
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables @Controller and @RequestMapping. Includes Tomcat Server.
MyService
http://localhost:8080/Hello
Tomcat
Browser
MyController
@Autowired
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_service_class (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside package controllers)
Create Package: services (inside main package)
– Create Class: MyService.java (inside package controllers)
MyService.java
package com.ivoronline.springboot_service_class_autowired.services;
import org.springframework.stereotype.Service;
@Service
public class MyService {
public String hello() {
return "Hello from Service";
}
}
MyController.java
package com.ivoronline.springboot_service_class_autowired.controllers;
import com.ivoronline.springboot_service_class_autowired.services.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@Autowired MyService myService;
@ResponseBody
@RequestMapping("/Hello")
public String hello() {
//CALL SERVICE
String result = myService.hello();
//RETURN RESULT
return result;
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/Hello
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>